const { ipcMain, net, shell } = require('electron')
const fs = require('fs')
const fsPromises = require('fs').promises
const path = require('path')
const { exec, spawn } = require('child_process')
const iconv = require('iconv-lite')

export const getLocalHost = () => {
    return new Promise((resolve, reject) => {
        fs.readFile('C:\\Windows\\System32\\drivers\\etc\\hosts','utf8', (err, data) => {
          if (err) {
            reject(err)
          }
          resolve(data)
        })
    })
}

export const getRemoteHost = () => {
    return new Promise((resolve, reject) => {
        const request = net.request('https://raw.hellogithub.com/hosts')
        request.on('response', (response) => {
    
          // console.log(`STATUS: ${response.statusCode}`)
          // console.log(`HEADERS: ${JSON.stringify(response.headers)}`)
          response.on('data', (chunk) => {
            // console.log(`BODY: ${chunk}`)
            resolve(chunk.toString())
          })
          response.on('end', () => {
            // console.log('No more data in response.')
          })
        })
        request.end()
    })
}

export const openFolder = (event, path) => {
    return shell.openPath(path)
}

export const updateFile = (event, filePath, fileStr) => {
    return fsPromises.writeFile(filePath, fileStr)
}

 export const updateDns = () => {
    return new Promise((resolve, reject) => {
        exec('ipconfig /flushdns', { encoding: 'cp936' }, (err, stdout) => {
            if (err) {
                console.error(iconv.decode(err, 'cp936'))
                reject(iconv.decode(err, 'cp936'))
                return
            }
            console.log(iconv.decode(stdout, 'cp936'))
            resolve(iconv.decode(stdout, 'cp936'))
        })
    })
    
 }